package com.xaicode.learn.netty.dubborpc.netty;

import com.xaicode.learn.support.InetConst;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 21:27
 */
@Slf4j
public class NettyServer {

    public static void startServer(String host, int port) {
        startServer0(host, port);
    }

    /**
     * init and start netty server.
     * <p><b>startServer0 for netty style.</b>
     *
     * @param host 127.0.0.1
     * @param port 6688
     * @see InetConst
     */
    private static void startServer0(String host, int port) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            final ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());

                            // add self handler
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            final ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();
            log.info("-- netty server started --");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
